package net.esj.basic.core.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;

public class FileUtils {

	public static final String[] saveOrUpdateFiles(String path,String name,FileItem fileItem) throws IOException{
		if(!path.endsWith(File.separator)){
			path += File.separator;
		}
		File[] tempFiles = fileItem.getFile();
		String[] tempFileNames = fileItem.getFileName();
		
		List<String> fileNames = new ArrayList<String>();
		for(int i=0;i<tempFiles.length;i++){
			String postfix = getFilePostfix(tempFileNames[i]);
			String tmpname = name;
			if(tempFiles.length>1){
				tmpname += "_"+(i+1);
			}
			final String fileRealName = tmpname;
			String pa = path+fileRealName+"."+postfix;
			
			File file = new File(pa);
			if(!file.getParentFile().exists()){
				file.getParentFile().mkdirs();
			}else{
				File[] oldfiles = file.getParentFile().listFiles(new FilenameFilter() {//删除旧的数据
					
					@Override
					public boolean accept(File dir, String name) {
						if(name.startsWith(fileRealName)){
							return true;
						}
						return false;
					}
				});
				for(File f : oldfiles){
					f.delete();
				}
			}
			org.apache.commons.io.FileUtils.copyFile(tempFiles[i], file);
			
			fileNames.add(pa);
		}
		return fileNames.toArray(new String[]{});
	}
	
	public static final void saveFile(String fileName , StringBuffer content,String code) throws IOException{
		File file = new File(fileName);
		if(!file.exists()){
			file.mkdirs();
			file.createNewFile();
		}
		FileOutputStream out = new FileOutputStream(file,true);
		out.write(content.toString().getBytes(code));
		out.close();
	}
	
	public static final String getFileContent(String fileName,String type) throws Exception{
		File file = new File(fileName);
		if(!file.exists()||file.isDirectory()){
			throw new FileNotFoundException(fileName);
		}
		InputStreamReader reader = new InputStreamReader(new FileInputStream(file), type);
		BufferedReader br = new BufferedReader(reader);
		String temp = null;
		StringBuffer sb = new StringBuffer();
		temp = br.readLine();
		while(temp!=null){
			sb.append(temp);
			temp = br.readLine();
		}
		return sb.toString();
	}
	
	private static String getFilePostfix(String name){
		if(name.lastIndexOf(".")>0){
			return name.substring(name.lastIndexOf(".")+1).toLowerCase();
		}
		return "";
	}
	
}
